package com.amazon.shop.controller;


import com.amazon.shop.aop.SystemLog;
import com.amazon.shop.constant.ReturnConstant;
import com.amazon.shop.entity.*;
import com.amazon.shop.exception.CustomException;
import com.amazon.shop.service.*;
import com.amazon.shop.service.impl.PermissionsServiceImpl;
import com.amazon.shop.service.impl.UsersServiceImpl;
import com.amazon.shop.utils.CommonResult;
import com.amazon.shop.vo.OrderPurchaseSaveVo;
import com.amazon.shop.vo.OrderPurchaseVo;
import com.amazon.shop.vo.ProductPicVo;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.BeanUtils;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.text.DateFormat;
import java.text.DecimalFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * <p>
 * 前端控制器
 * </p>
 *
 * @author 郭非
 * @since 2021-06-12
 */
@RestController
@RequestMapping("/shop/order-purchase")
@Api(tags = "采购单模块")
public class OrderPurchaseController {

    @Resource
    private OrderSimpleService orderSimpleService;
    @Resource
    private CommodityService commodityService;
    @Resource
    private ProductPicService productPicService;
    @Resource
    private OrderWayBillService orderWayBillService;
    @Resource
    private OrderPurchaseService orderPurchaseService;
    @Resource
    private PermissionsServiceImpl permissionsService;
    @Resource
    private UsersServiceImpl usersService;

    @SystemLog(value = "添加采购单")
    @PostMapping("/addPurchaseOrder")
    @ApiOperation(value = "添加采购单")
    @Transactional
    public CommonResult addPurchaseOrder(@RequestBody OrderPurchaseSaveVo orderPurchaseSaveVo,
                                         String orderNumber, String token) {
        boolean flag = permissionsService.getPermissionList(token, "38");
        if (flag) {
            OrderPurchase orderPurchase = new OrderPurchase();
            Orders orders = orderSimpleService.getById(orderNumber);

            BeanUtils.copyProperties(orderPurchaseSaveVo, orderPurchase);

            //处理采购单号
            String amazonOrderId = orders.getAmazonOrderId();
            String oddNumber = amazonOrderId.replace("-", "") + "purchase";
            orderPurchase.setOddNumber(oddNumber);

            //处理采购单图片
            String commodityId = orders.getCommodityId();
            Commodity commodity = commodityService.getById(commodityId);
            String sku = commodity.getSku();
            QueryWrapper<ProductPic> productPicWrapper = new QueryWrapper<>();
            productPicWrapper.eq("sku", sku);
            ProductPic productPic = productPicService.getOne(productPicWrapper);
            String path = productPic.getPath();
            orderPurchase.setPixMap(path);

            //处理转运商姓名
            QueryWrapper<OrderWayBill> orderWayBillQueryWrapper = new QueryWrapper<>();
            orderWayBillQueryWrapper.eq("about_order", orderNumber);
            OrderWayBill orderWayBill = orderWayBillService.getOne(orderWayBillQueryWrapper);
            orderPurchase.setTransportName(orderWayBill.getPurchaseName());
            orderPurchase.setTransportCenter(orderWayBill.getPurchaseCenter());

            //处理时间
            Date placeTime = orderPurchaseSaveVo.getPlaceTime();
            DateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            String date = format.format(placeTime);
            orderPurchase.setGmtCreated(date);

            //处理费用
            String money = orderPurchaseSaveVo.getMoney();
            BigDecimal decimal = new BigDecimal(money);
            orderPurchase.setMoney(decimal);

            orderPurchase.setOrderId(orderNumber);
            boolean save = orderPurchaseService.save(orderPurchase);
            String userRealName = usersService.getUserRealName(token);
            if (save) {
                return CommonResult.success("添加采购单成功")
                        .put("list", oddNumber)
                        .put("salesman", userRealName);
            } else {
                return CommonResult.error("添加采购单失败");
            }
        } else {
            throw new CustomException(ReturnConstant.NO_PERMISSION_CODE
                    , ReturnConstant.NO_PERMISSION_MESSAGE);
        }
    }

    @GetMapping("/getPurchaseOrders")
    @ApiOperation(value = "获取采购单列表")
    public CommonResult getPurchaseOrders(String token) {
        boolean flag = permissionsService.getPermissionList(token, "49");
        if (flag) {
            List<OrderPurchaseVo> orderPurchaseVos = new ArrayList<>();
            List<OrderPurchase> list = orderPurchaseService.list();
            for (OrderPurchase orderPurchase : list) {
                OrderPurchaseVo orderPurchaseVo = null;
                try {
                    orderPurchaseVo = new OrderPurchaseVo();
                    BeanUtils.copyProperties(orderPurchase, orderPurchaseVo);

                    System.out.println(orderPurchase.getMoney());
                    //处理订购单图片
                    String orderId = orderPurchase.getOrderId();
                    Orders orders = orderSimpleService.getById(orderId);
                    String commodityId = orders.getCommodityId();
                    Commodity commodity = commodityService.getById(commodityId);
                    String sku = commodity.getSku();
                    QueryWrapper<ProductPic> productPicWrapper = new QueryWrapper<>();
                    productPicWrapper.eq("sku", sku);
                    ProductPic productPic = productPicService.getOne(productPicWrapper);
                    ProductPicVo productPicVo = new ProductPicVo();
                    productPicVo.setPath(productPic.getPath());
                    orderPurchaseVo.setPixMap(productPicVo);
                    //处理费用
                    BigDecimal money = orderPurchase.getMoney();
                    DecimalFormat decimalFormat = new DecimalFormat("0.0");
                    String floatString = decimalFormat.format(money);
                    orderPurchaseVo.setMoney(floatString);
                } catch (Exception e) {
                    e.printStackTrace();
                }
                orderPurchaseVos.add(orderPurchaseVo);
            }
            return CommonResult.success("查询成功").put("orderPurchaseList", orderPurchaseVos);
        } else {
            throw new CustomException(ReturnConstant.NO_PERMISSION_CODE
                    , ReturnConstant.NO_PERMISSION_MESSAGE);
        }
    }


    @SystemLog(value = "删除采购单")
    @PostMapping("/deletePurchaseOrder")
    @ApiOperation(value = "删除采购单")
    public CommonResult deletePurchaseOrder(String token, String id) {
        boolean flag = permissionsService.getPermissionList(token, "38");
        if (flag) {
            boolean remove = orderPurchaseService.removeById(id);
            if (remove) {
                String userRealName = usersService.getUserRealName(token);
                return CommonResult.success("删除成功")
                        .put("list", remove)
                        .put("salesman", userRealName);
            }
            return CommonResult.error("删除失败");
        } else {
            throw new CustomException(ReturnConstant.NO_PERMISSION_CODE
                    , ReturnConstant.NO_PERMISSION_MESSAGE);
        }
    }
}